package ch18._02;

import java.util.Random;

public class Solution {

    public static int[] init(int k) {
	if (k < 0)
	    return null;
	if (k == 0) {
	    return new int[]{};
	}
	int[] A = new int[k];
	for (int i = 0; i < k; i++) {
	    A[i] = i + 1;
	}
	return A;
    }

    public static void shuffle(int[] A) {
	if (null == A || A.length <= 1) {
	    return;
	}
	Random random = new Random();
	for (int i = 0; i < A.length - 1; i++) {
	    int r = i + random.nextInt(A.length - i);
	    swap(A, r, i);
	}
    }

    private static void swap(int[] A, int r, int i) {
    	int i1 = A[r], i2 = A[i];
    	/**
    	 * Good Question.
    	 * If i and r are equal, A[r] and A[i] is the same location in memory. Ahhhhhh!!
    	 */
    	/**
		A[r] ^= A[i];
		A[i] ^= A[r];
		A[r] ^= A[i];
		*/
    	/**
    	A[r] = A[r] ^ A[i];
    	A[i] = A[r] ^ A[i];
    	A[r] = A[r] ^ A[i];
    	*/
    	int tmp = A[i];
    	A[i] = A[r];
    	A[r] = tmp;
	if (A[i] != i1 || A[r] != i2) {
		System.err.println("What the hell?!" + "(A[r], A[i]) were (" + i1 + ", " + i2 + "),"
				+ " now they are (" + A[r] + ", " + A[i] + ").");
	}
    	
    }

    public static void print(int[] A) {
	if (null == A || A.length == 0) {
	    return;
	}
	for (int i = 0; i < A.length; i++) {
		if (i % 13 == 0) {
			System.out.println();
		}
		System.out.print(A[i] + "\t");
	}
	System.out.println();
    }

    public static void main(String... args) {
	int k = 52;
	int[] A = init(k);
	System.out.println("The deck looks like:");
	print(A);
	shuffle(A);
	System.out.println("After shuffling:");
	print(A);
    }
}